package com.wanji.gateway;

import com.wanji.gateway.config.GatewayConfig;
import com.wanji.gateway.device.DeviceManager;
import com.wanji.gateway.handler.DeviceMessageHandler;
import com.wanji.gateway.protocol.ProtocolManager;
import com.wanji.protocol.api.Protocol;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import jakarta.annotation.PreDestroy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RequiredArgsConstructor
public class NettyApplication implements CommandLineRunner {

    private final GatewayConfig gatewayConfig;
    private final ProtocolManager protocolManager;
    private final DeviceManager deviceManager;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Override
    public void run(String... args) {
        bossGroup = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory());
        workerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());

        try {
            for (int port : gatewayConfig.getPorts()) {
                new ServerBootstrap()
                        .group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) {
                                Protocol protocol = protocolManager.getProtocol(ch.remoteAddress());
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline
                                        .addLast(new GlobalTrafficShapingHandler(
                                                bossGroup,
                                                gatewayConfig.getWriteLimit(),
                                                gatewayConfig.getReadLimit(),
                                                gatewayConfig.getCheckInterval()))
                                        .addLast(new IdleStateHandler(30, 0, 0, TimeUnit.SECONDS));

                                // 初始化协议编解码器
                                pipeline.addLast(new LoggingHandler());
                                protocol.init(pipeline);
                                pipeline.addLast(new DeviceMessageHandler(deviceManager));
                            }
                        })
                        .bind(port).addListener(future -> {
                            if (future.isSuccess()) {
                                log.info("TCP服务启动成功, 端口: {}", port);
                            } else {
                                log.error("TCP端口绑定失败: {}", port, future.cause());
                            }
                        });
            }
        } catch (Exception e) {
            log.error("TcpServer start error", e);
        }
    }

    @PreDestroy
    public void stop() throws InterruptedException {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully().sync();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully().sync();
        }
        log.info("Netty TCP 服务器已停止.");
    }
}